<?php
/**
 *
 * @author quick
 *
 */
namespace Addons\Crop\Controller;

use Home\Controller\AddonsController;

require_once('ThinkPHP/Library/Vendor/PHPImageWorkshop/ImageWorkshop.php');

use PHPImageWorkshop\Core\ImageWorkshopLayer;
use PHPImageWorkshop\ImageWorkshop;

class CropController extends AddonsController
{

    public function doCrop()
    {
        $picture_id = I('request.picture_id');
        $crop = I('request.crop');
        //检查参数
        if (!$picture_id) {
            $this->error('图片ID不能为空');
        }
        $o_path = get_cover($picture_id, 'path');
        if (!$o_path) {
            $this->error('找不到图片');
        }
        //裁剪图片
        $path = $this->cropPicture($o_path, $crop);
        $return = array('path' => $path);
        $this->success($return);
    }

    private function cropPicture($path, $crop = null)
    {
        //如果不裁剪，则发生错误
        if (!$crop) {
            $this->error('必须裁剪');
        }

        $path = preg_replace('/^.*?\/Uploads/', '/Uploads', $path);


        //获取文件路径

        $fullPath = substr($path,0,1) =='/'?'.' . $path : $path;
        //生成文件名后缀
        $postfix = substr(md5($crop), 0, 8);
        $savePath = preg_replace('/\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $fullPath);
        $returnPath = preg_replace('/\.[a-zA-Z0-9]*$/', '-' . $postfix . '$0', $path);
        $returnPath = substr($returnPath,0,1) =='/'?'.' . $returnPath : $returnPath;

        //解析crop参数
        $crop = explode(',', $crop);
        $x = $crop[0];
        $y = $crop[1];
        $width = $crop[2];
        $height = $crop[3];

        //是sae则不需要获取全路径
        if (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'local') {
            //本地环境

            $returnPath = str_replace('/Uploads/', '/Uploads/tmp/' . is_login() . '/', $returnPath);
            $savePath = str_replace('/Uploads/', '/Uploads/tmp/' . is_login() . '/', $savePath);

            $image = ImageWorkshop::initFromPath($fullPath);

            //生成将单位换算成为像素
            $x = $x * $image->getWidth();
            $y = $y * $image->getHeight();
            $width = $width * $image->getWidth();
            $height = $height * $image->getHeight();

            //如果宽度和高度近似相等，则令宽和高一样
            if (abs($height - $width) < $height * 0.01) {
                $height = min($height, $width);
                $width = $height;
            }


            //调用组件裁剪头像
            $image = ImageWorkshop::initFromPath($fullPath);
            $image->crop(ImageWorkshopLayer::UNIT_PIXEL, $width, $height, $x, $y);
            $image->save(dirname($savePath), basename($savePath));
            //返回新文件的路径
            return $returnPath;
        } elseif (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'sae') {
            //sae
            //载入临时头像
            $f = new \SaeFetchurl();
            $img_data = $f->fetch($fullPath);
            $img = new \SaeImage();
            $img->setData($img_data);
            $img_attr = $img->getImageAttr();


            //生成将单位换算成为像素
            $x = $x * $img_attr[0];
            $y = $y * $img_attr[1];
            $width = $width * $img_attr[0];
            $height = $height * $img_attr[1];

            //如果宽度和高度近似相等，则令宽和高一样
            if (abs($height - $width) < $height * 0.01) {
                $height = min($height, $width);
                $width = $height;
            }
            $img->crop($x / $img_attr[0], ($x + $width) / $img_attr[0], ($y) / $img_attr[1], ($y + $height) / $img_attr[1]);
            $new_data = $img->exec();
            $storage = new \SaeStorage();
            $thumbFilePath = str_replace(C('UPLOAD_SAE_CONFIG.rootPath'), '', dirname($savePath) . '/' . basename($savePath));
            $thumbed = $storage->write(C('UPLOAD_SAE_CONFIG.domain'), $thumbFilePath, $new_data);
            //返回新文件的路径
            return $thumbed;
        } elseif (strtolower(C('PICTURE_UPLOAD_DRIVER')) == 'qiniu') {

            $imageInfo = file_get_contents($fullPath . '?imageInfo');
            $imageInfo = json_decode($imageInfo);

            //生成将单位换算成为像素
            $x = $x * $imageInfo->width;
            $y = $y * $imageInfo->height;
            $width = $width * $imageInfo->width;
            $height = $height * $imageInfo->height;
            $new_img = $fullPath . '?imageMogr2/crop/!' . $width . 'x' . $height . 'a' . $x . 'a' . $y;
            //返回新文件的路径
            return $new_img;
        }

    }

    public function confirm()
    {
        $path = I('request.path');
        if (is_login()) {
            if(!file_exists($path)){
                $this->error('文件不存在');
            }
            $new_path = str_replace('/Uploads/tmp/' . is_login() . '/', '/Uploads/', $path);
            $num = substr($path,0,1) =='/'?1 : 0;
            $save_path = str_replace('/Uploads/tmp/' . is_login() . '/', '/Uploads/', substr($path, $num));
            $data = array('type' => strtolower(C('PICTURE_UPLOAD_DRIVER')), 'path' => $save_path, 'status' => 1, 'create_time' => time());
            $res = D('Picture')->add($data);
            if ($res) {
                rename($path, $new_path);
                $this->deldir('./Uploads/tmp/' . is_login() . '/');
                $result=array('id'=>$res,'path'=>$new_path);
                $this->success($result);
            } else {
                $this->error('保存失败');
            }
        } else {
            $this->error('请登录');
        }

    }


    protected function deldir($dir)
    {
        //先删除目录下的文件：
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    $this->deldir($fullpath);
                }
            }
        }

        closedir($dh);
        //删除当前文件夹：
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }

}